import React, { Component } from "react"
import { withRouter } from "react-router";
import styles from './equip.less'
import Toast from '@/utils/toast'
import { equipRecommendList, userEquipBind, equipList } from '@/services';

class BindEquip extends Component {

  constructor(props){
    super(props);
    this.state = {
      recList: [],
      search: ''
    }
  }

  async componentDidMount(){
    try {
      const { data } = await equipRecommendList();
      this.setState({ recList: data })
    } catch (error) {
      console.log(error);
    }
  }

  handleBind = async(code) => {
    try {
      const data = await userEquipBind({ equipCode: code });
      if(data.code==200){
        Toast.success('绑定成功');
        this.handleSearch();
      }
    } catch (error) {
      console.log(error)
    }
  }

  handleSearch = async() => {
    try {
      const { data } = await equipList({ equipCode: this.state.search });
      this.setState({ recList: data })
    } catch (error) {
      console.log(error);
    }
  }

  onChange = (e) => {
    this.setState({
      search: e.target.value
    })
  }
  
  render(){
    return (
      <div>
        <div className={styles.header}>
          <img className={styles.top_bg} src={require('../assets/img/home/top_bg.png')} />
          <div className={styles.content}>
            <img onClick={()=>{ this.props.history.replace('/') }} className={styles.back} src={require('../assets/img/back.png')} />
            绑定设备
          </div>
        </div>
        <div className={styles.container}>
          <div className={styles.search}>
            <input placeholder="请输入设备编号" className={styles.search_input} value={this.state.search} onChange={this.onChange}  />
            <img onClick={this.handleSearch} src={require('../assets/img/equip/search.png')} className={styles.search_icon} />
          </div>
          <div className={styles.title}>推荐设备</div>
          <div className={styles.list}>
            {this.state.recList.map((data)=>(
              <div key={data.equipCode} className={styles.item}>
                <div className={styles.item_left}>{data.equipCode}</div>
                {Number(data.status) ? <div className={styles.item_right_binded}>已绑定</div> : <div onClick={()=> this.handleBind(data.equipCode)} className={styles.item_right_bind}>绑定</div>}
              </div>
            ))}
          </div>
        </div>
        <div className={styles.bottom} onClick={()=>{ this.props.history.replace('/') }}>
          <div className={styles.bottom_btn}>返 回</div>
        </div>
      </div>
    )
  }
}
export default withRouter(BindEquip)